﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class Level4X9 : MonoBehaviour
{
    public GameLevelItem gameLevelItem;
    private bool isWin = false;
    public List<TextButton> tbList = new List<TextButton>();
    public List<TextButton> loveTbList = new List<TextButton>();
    private List<int> tbIndexList = new List<int>();
    private List<int> loveTbIndexList = new List<int>();

    public Color normalColor = Color.white;
    public Color activeColor = Color.gray;
    // Start is called before the first frame update
    void Start()
    {
        InitTbList();
    }

    private void InitTbList()
    {
        int count = tbList.Count;
        for (int i = 0; i < count; i++)
        {
            int tempIndex = i;
            tbList[tempIndex].Init(string.Empty, () =>
            {
                if (isWin) return;
                if (tbIndexList.Contains(tempIndex))
                {
                    tbList[tempIndex].button.image.color = normalColor;
                    tbIndexList.Remove(tempIndex);
                }
                else
                {
                    tbList[tempIndex].button.image.color = activeColor;
                    tbIndexList.Add(tempIndex);
                }
                TriggerWin();
            });
            //tbList[i]
        }
        count = loveTbList.Count;
        for (int i = 0; i < count; i++)
        {

            int tempIndex = i;
            loveTbList[tempIndex].Init(loveTbList[tempIndex].text.text, () =>
            {
                if (isWin) return;
                if (loveTbIndexList.Contains(tempIndex))
                {
                    loveTbList[tempIndex].button.image.color = normalColor;
                    loveTbIndexList.Remove(tempIndex);
                }
                else
                {
                    loveTbList[tempIndex].button.image.color = activeColor;
                    loveTbIndexList.Add(tempIndex);
                }
                TriggerWin();
            });
            loveTbList[tempIndex].text.DOFade(0, 0);
        }
    }


    private void TriggerWin()
    {
        if (tbIndexList.Count < 1 && loveTbIndexList.Count == 4)
        {
            isWin = true;
            int count = loveTbList.Count;
            for (int i = 0; i < count; i++)
            {
                loveTbList[i].button.image.DOColor(normalColor, 0.5f);
                loveTbList[i].text.DOFade(1, 0.5f);
            }
            Invoke("TriggerResult", 1);
        }
    }

    private void TriggerResult()
    {
        gameLevelItem.TriggerResult(true);
    }

}
